package com.imooc.web.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Zqm
 * @Title: TimeInterceptor
 * @ProjectName imooc-security
 * @date 2018/12/17
 * 自定义拦截器
 */
@Component
public class TimeInterceptor implements HandlerInterceptor {


    /**
     * 控制器方法  调用之前
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println(" preHandle");
        System.out.println(((HandlerMethod)o).getBean().getClass().getName());  //类名
        System.out.println(((HandlerMethod)o).getMethod().getName());       //方法名

        httpServletRequest.setAttribute("startTime",System.currentTimeMillis());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

        System.out.println(" postHandle");

        System.out.println("time interceptor  耗时："+(System.currentTimeMillis()-(long)httpServletRequest.getAttribute("startTime")));
    }

    /**
     * 控制器方法完成之后  都会被调用
     * 拦截器会拦截所有控制器的方法  包括spring  basicController的方法
     * 拦截器会在自定义异常拦截之后走  需要注意
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("afterCompletion");
        System.out.println("time interceptor  耗时："+(System.currentTimeMillis()-(long)httpServletRequest.getAttribute("startTime")));
        System.out.println("ex is "+e);
    }
}
